package com.sita.bike.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.utils.L;
import com.sita.bike.R;
import com.sita.bike.beans.PersonBean;
import com.sita.bike.event.PersonalInfoUpdateEvent;
import com.sita.bike.model.EaseUser2;
import com.sita.bike.model.PersonalInfo;
import com.sita.bike.model.PersonalInfoListener;
import com.sita.bike.persistence.GroupChatDetailEvent;
import com.sita.bike.persistence.GroupChatDetailEventDao;
import com.sita.bike.persistence.GroupMember;
import com.sita.bike.persistence.Person;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.Account;
import com.sita.bike.rest.model.Account3;
import com.sita.bike.rest.model.GroupCreateResponseData;
import com.sita.bike.rest.model.RestResponse;
import com.sita.bike.rest.model.request.GetAccountRequest;
import com.sita.bike.rest.model.request.GetRtResourceCountRequest;
import com.sita.bike.rest.model.response.GetAccountResponse;
import com.sita.bike.rest.model.response.MileageSummaryRankingResponse;
import com.sita.bike.rest.model.response.MileageSummaryResponse;
import com.sita.bike.rest.model.response.RtResourcesCountResponse;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.task.MemberAvatarListLoadTask;
import com.sita.friend.FriendHelper;
import com.sita.friend.db.DBManager;
import com.sita.friend.db.UserDao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

/**
 * Created by hongyun on 2016/1/12.
 */
public class AccountUtils {

    // Session saved data, cached in memory
    private static String mAccountId;
    private static String mUserName;
    private static String mNickName;
    private static String mMobile;
    private static String mAvatar;
    private static Person mPerson;
    private static Drawable mHeadImg = null;
    // Personal recording info;
    private static long mRank;
    private static Double mMileage;
    private static Long mTotalTime;

    public static Double getMileage() {
        return mMileage;
    }

    public static Long getTotalTime() {
        return mTotalTime;
    }

    public static long getRank() {
        return mRank;
    }

    public static void getMileageInfoAsync() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("accountId", mAccountId);
        RestClient.getRestNormalService().mileageSummaryForAccount(params, new Callback<MileageSummaryResponse>() {
            @Override
            public void success(MileageSummaryResponse mileageSummaryResponse, Response response) {
                if (mileageSummaryResponse.errorCode.equals("0")) {
                    mMileage = mileageSummaryResponse.data.mileage;
                    mTotalTime = mileageSummaryResponse.data.period;
                    PersonalInfoUpdateEvent event = new PersonalInfoUpdateEvent();
                    event.mMileage = mMileage;
                    event.mTotalTime = mTotalTime;
                    EventBus.getDefault().post(event);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                L.e("getMileageInfoAsync()", error);
            }
        });

    }


    public static void getRankingInfoAsync(final PersonalInfoListener listener) {
        if (TextUtils.isEmpty(mAccountId)) {
            mAccountId = LocalStorage.getAccountId();
        }
        RestClient.getRestNormalService().mileageSummaryRanking(mAccountId, new Callback<MileageSummaryRankingResponse>() {
            @Override
            public void success(MileageSummaryRankingResponse cntResponse, Response response) {
                if (cntResponse.errorCode.equals("0")) {
                    mRank = cntResponse.data.ranking;
                    PersonalInfoUpdateEvent event = new PersonalInfoUpdateEvent();
                    event.mRank = mRank;
                    EventBus.getDefault().post(event);
                    PersonalInfo personalInfo = new PersonalInfo();
                    personalInfo.setRank(mRank);
                    listener.Success(personalInfo);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                L.e("getRankingInfoAsync()", error);
            }
        });
    }

    public static void getTrackInfoAsync(final PersonalInfoListener listener) {
        if (TextUtils.isEmpty(mAccountId)) {
            mAccountId = LocalStorage.getAccountId();
        }
        Map<String, String> params = new HashMap<String, String>();
        params.put("accountId", mAccountId);
        RestClient.getRestNormalService().mileageSummaryForAccount(params, new Callback<MileageSummaryResponse>() {
            @Override
            public void success(MileageSummaryResponse mileageResponse, Response response) {
                if (mileageResponse.errorCode.equals("0") && mileageResponse.data != null) {
                    Double mileage = mileageResponse.data.mileage;
                    Long period = mileageResponse.data.period;
                    if (mileage == null) {
                        mileage = new Double(0f);
                    }
                    if (period == null) {
                        period = new Long(0);
                    }
                    PersonalInfo personalInfo = new PersonalInfo();
                    personalInfo.setTotal(mileage.doubleValue());
                    personalInfo.setTime(period.longValue());
                    listener.Success(personalInfo);
                } else if (mileageResponse.errorCode.equals("0")) {
                    PersonalInfo personalInfo = new PersonalInfo();
                    personalInfo.setTotal(0f);
                    personalInfo.setTime(0);
                    listener.Success(personalInfo);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                com.sita.tboard.ui.tools.L.e("getTrackInfoAsync()", error);
            }
        });
    }

    public static void getTrendCountAsync(final PersonalInfoListener listener) {
        if (TextUtils.isEmpty(mAccountId)) {
            mAccountId = LocalStorage.getAccountId();
        }
        GetRtResourceCountRequest cntReq = new GetRtResourceCountRequest();
        cntReq.accountId = mAccountId;
        RestClient.getRestNormalService().rtResourcesCount(cntReq, new Callback<RtResourcesCountResponse>() {
            @Override
            public void success(RtResourcesCountResponse cntResponse, Response response) {
                if (cntResponse.errorCode.equals("0")) {
                    long count = 0;
                    if (cntResponse.data != null) {
                        count = cntResponse.data.resourcesCount;
                    }
                    PersonalInfo personalInfo = new PersonalInfo();
                    personalInfo.setTrendCount(count);
                    listener.Success(personalInfo);
                }
            }

            @Override
            public void failure(RetrofitError error) {
                com.sita.tboard.ui.tools.L.e("getTrendCountAsync()", error);
            }
        });
    }

    public static void resetAccountCacheInfo() {
        mAccountId = null;
        mUserName = null;
        mNickName = null;
        mAvatar = null;
        mMobile = null;
        mPerson = null;
        mHeadImg = null;

        mRank = -1;
        mMileage = null;
        mTotalTime = null;
    }

    public static String getAccountID() {
        if (TextUtils.isEmpty(mAccountId)) {
            mAccountId = String.valueOf(PersistUtils.findPersonBean().credential.getXmppUser());
        }
        return mAccountId;
    }

    public static Drawable getAccountHeader(Context context) {
        PersonBean personBean = PersistUtils.findPersonBean();
        if (null != personBean.person.getPhoto()) {
            Bitmap bitmap = BitmapUtils.bytesToBitmap(personBean.person.getPhoto());
            mHeadImg = new BitmapDrawable(context.getResources(), bitmap);
        }
        return mHeadImg;
    }

    public static void setHeadImage(Drawable headImage) {
        mHeadImg = headImage;
    }

    public static Drawable getDefaultAccountHeader(Context context) {
        return context.getResources().getDrawable(R.drawable.umeng_socialize_default_avatar);
    }

    public static void setUserName(String userName) {
        mUserName = userName;
    }

    public static String getUserDisplayName() {
        if (TextUtils.isEmpty(mUserName)) {
            PersonBean personBean = PersistUtils.findPersonBean();
            if (personBean.person.getName() != null) {
                mUserName = personBean.person.getName();
            } else if (personBean.person.getMobile() != null) {
                mUserName = personBean.person.getMobile();
            }
        }
        return mUserName;
    }

    public static String getMobile() {
        PersonBean personBean = PersistUtils.findPersonBean();
        mMobile = personBean.person.getMobile();
        return mMobile;
    }

    public static void setNickName(String nickName) {
        mNickName = nickName;
    }

    public static String getNickName() {
        if (TextUtils.isEmpty(mNickName)) {
            PersonBean personBean = PersistUtils.findPersonBean();
            if (personBean.person.getName() != null) {
                mNickName = personBean.person.getName();
            }
        }
        return mNickName;
    }

    public static String getAvatar() {
        if (TextUtils.isEmpty(mAvatar)) {
            PersonBean personBean = PersistUtils.findPersonBean();
            mAvatar = personBean.person.getAvatarUrl();
        }
        return mAvatar;
    }


    public static boolean isSameUser(String accountid) {
        return TextUtils.isEmpty(accountid) ? false : accountid.equals(getAccountID());
    }

    public static void SetHeaderName(ImageView view, TextView text, Context context) {
        Drawable drawable = getAccountHeader(context);
        if (drawable == null) {
            drawable = getDefaultAccountHeader(context);
            view.setImageDrawable(drawable);
            ImageLoader.getInstance().displayImage(AccountUtils.getAvatar(), view);
        } else {
            view.setImageDrawable(drawable);
        }

        if (text != null) {
            text.setText(getUserDisplayName());
        }

    }

    public static void SetFriendHeaderName(String username, ImageView view, TextView text, Context context) {

        EaseUser2 user2 = FriendHelper.getInstance().getContactList().get(username);

        if (user2 != null) {
            Drawable drawable = getDefaultAccountHeader(context);

            view.setImageDrawable(drawable);
            if (!TextUtils.isEmpty(user2.getAvatar())) {
                view.setTag(user2.getAvatar());
                ImageManager.loadImage(view, user2.getAvatar());
//                ImageLoader.getInstance().displayImage(user2.getAvatar(), view);
            }
            if (text != null) {
//                text.setText(getUserDisplayName());
                text.setText(getSenderName(user2));
            }
        }

    }

    public static void SetMemberHeaderName(String username, ImageView view, TextView text, Context context) {
        GroupMember groupMember = PersistUtils.getGroupMember(username);

        if (groupMember != null) {
            Drawable drawable = getDefaultAccountHeader(context);
            view.setImageDrawable(drawable);
            if (!TextUtils.isEmpty(groupMember.getAvatarUrl())) {
                view.setTag(groupMember.getAvatarUrl());
                ImageManager.loadImage(view, groupMember.getAvatarUrl());
//                ImageLoader.getInstance().displayImage(user2.getAvatar(), view);
            }
            if (text != null) {
                text.setText(groupMember.getNickname());
            }
        }

    }

    public static String getSenderName(EaseUser2 user2) {
        String senderName = null;
        if (user2.getNick() != null) {
            senderName = user2.getNick();
        } else if (user2.getUsername() != null) {
            senderName = user2.getUsername();
        } else if (user2.getMobile() != null) {
            senderName = user2.getMobile();
        }
        return senderName;
    }

    public static String getUserDisplayName(Account account) {
        String senderName;
        if (!TextUtils.isEmpty(account.mNickName)) {
            senderName = account.mNickName;
        } else {
            senderName = account.mMobile;
        }
        return senderName;
    }


    public static void SetFriendHeaderNick(String username, ImageView view, TextView text, Context context) {
        EaseUser2 user2 = FriendHelper.getInstance().getContactList().get(username);
        if (user2 != null) {
            Drawable drawable = getDefaultAccountHeader(context);
            view.setImageDrawable(drawable);
            if (!TextUtils.isEmpty(user2.getAvatar())) {
                ImageLoader.getInstance().displayImage(user2.getAvatar(), view);
            }
            if (text != null) {
                text.setText(user2.getNick() != null ? user2.getNick() : user2.getNick());
            }
        }

    }

    public static void setUserHeaderName(String username, String mAvatar, ImageView view, TextView text, Context context) {

        if (text != null) {
            text.setText(username);
        }

        if (!TextUtils.isEmpty(mAvatar)) {
            view.setTag(mAvatar);
            ImageManager.loadImage(view, mAvatar);
        }

    }

    public static void addUserAvatar(String key, Bitmap bitmap) {
        if (GlobalContext.mMemoryCache.get(key) == null) {
            GlobalContext.mMemoryCache.put(key, bitmap);
        }
    }

    public static Bitmap getUserAvatar(String key) {
        return GlobalContext.mMemoryCache.get(key);
    }

    public static void addMemberAvatar(String key, Bitmap bitmap) {
        if (GlobalContext.mMemoryCache.get(key) == null) {
            GlobalContext.mMemoryCache.put(key, bitmap);
        }
    }

    public static Bitmap getMemberAvatar(String key) {
        return GlobalContext.mMemoryCache.get(key);
    }

    /*
    * save friend list
     */
    public static void saveFriendList(List<Account3> userlist) {

        Map<String, EaseUser2> localuserlist = new HashMap<String, EaseUser2>();
        for (Account3 account : userlist
                ) {
            String name = (TextUtils.isEmpty(account.mNickName) ? account.mMobile : account.mNickName);
            EaseUser2 user = new EaseUser2(name);
            user.setAccountId(account.mAccountId);
            user.setMobile(account.mMobile);
            user.setGender(String.valueOf(account.mGender));
            user.setAvatar(account.mAvatar);
            user.setNick(account.mNickName);

            localuserlist.put(name, user);
        }
        // 存入内存
        FriendHelper.getInstance().getContactList().clear();
        FriendHelper.getInstance().getContactList().putAll(localuserlist);
        // 存入db
        UserDao dao = new UserDao(GlobalContext.getGlobalContext());
        List<EaseUser2> users = new ArrayList<EaseUser2>(localuserlist.values());
        dao.saveContactList(users);

    }

    public static void saveFriend(Account account) {
        String name = (TextUtils.isEmpty(account.mNickName) ? account.mMobile : account.mNickName);
        EaseUser2 user = new EaseUser2(name);
        user.setAccountId(account.mAccountId);
        user.setMobile(account.mMobile);
        user.setGender(String.valueOf(account.mGender));
        user.setAvatar(account.mAvatar);
        user.setNick(account.mNickName);
        // 存入内存
        FriendHelper.getInstance().getContactList().put(name, user);
        // 存入db
        UserDao dao = new UserDao(GlobalContext.getGlobalContext());
        dao.saveContact(user);
    }

    public static void savePendingFriend(Account account) {
        PersistUtils.saveGroupMember(account);
    }

    public interface AsyncFetchFriendInfoListener {
        public void success(Account account);

        public void failed();
    }

    public static void asyncFetchFriendInfo(String accountId, final AsyncFetchFriendInfoListener listener) {
        GetAccountRequest request = new GetAccountRequest();
        request.accountId = accountId;
        RestClient.getRestNormalService().accountGet(request, new Callback<GetAccountResponse>() {
                    @Override
                    public void success(GetAccountResponse getAccountResponse, Response response) {
                        Account account = getAccountResponse.account;
                        listener.success(account);
//                        NoSQLEntity<Account> entity = new NoSQLEntity<Account>(Constants.ACCOUNT_BUCKET, mAccountId, account);
//                        NoSQL.with(GlobalContext.getGlobalContext()).using(Account.class)
//                                .save(entity);
                    }

                    @Override
                    public void failure(RetrofitError error) {
//                        L.e(error);
//                        if (error.getKind() == RetrofitError.Kind.NETWORK) {
//                            Toast.makeText(FriendDetailActivity.this, error.getMessage(), Toast.LENGTH_SHORT).show();
//                        }
                    }
                }

        );

    }

    /**
     * 保存群组中非好友GroupMember信息
     *
     * @param groupId   群组id
     * @param isImGroup isImGroup为true时，groupId为环信ID，为false,groupID为思塔服务器ID
     */
    public static void saveGroupMembers(String groupId, boolean isImGroup) {

        // Request Group Info from sita server.
        RestClient.getRestNormalService().getGroupDetail(groupId, isImGroup, new Callback<RestResponse>() {
            @Override
            public void success(RestResponse restResponse, Response response) {
                Log.d("Group Invitation", "Ok");
                //保存环信群组id,服务器id
                GroupCreateResponseData groupCreateResponseData = RestClient.getGson().fromJson(RestClient.getGson().toJson(restResponse.mData), GroupCreateResponseData.class);
                String targetid = groupCreateResponseData.mGroupId;
                String groupid = groupCreateResponseData.mImGroupId;
                //获取创建者id
                Account owner = groupCreateResponseData.mOwner;
                String accountid = owner.mAccountId;
                //判断是不是创建者
                if (!(accountid.equals(AccountUtils.getAccountID()))) {
                    //取得群组内member列表
                    List<Account> members = groupCreateResponseData.mMember;
                    List<String> avatarUrlList = new ArrayList<String>();
                    Iterator<Account> iterator = members.iterator();
                    while (iterator.hasNext()) {
                        //判断是否为好友关系,若否，存入memberlist
                        Account member = iterator.next();
                        Map<String, EaseUser2> contactlist = DBManager.getInstance().getContactList();
                        if (!(contactlist.containsKey(member.mNickName) || contactlist.containsKey(member.mMobile)) && !(member.mAccountId.equals(AccountUtils.getAccountID()))) {
                            PersistUtils.saveGroupMember(member);
                            avatarUrlList.add(member.mAvatar);
                        }
                    }
                    if (avatarUrlList.size() > 0) {
                        new MemberAvatarListLoadTask(avatarUrlList).execute();
                    }
                }
                GroupChatDetailEvent groupChatDetailEvent = new GroupChatDetailEvent();
                groupChatDetailEvent.setGroupid(groupid);
                groupChatDetailEvent.setTargetid(targetid);
                GroupChatDetailEventDao groupChatDetailEventDao = GlobalContext.getDaoSession().getGroupChatDetailEventDao();
                groupChatDetailEventDao.insert(groupChatDetailEvent);
            }

            @Override
            public void failure(RetrofitError error) {
                Log.d("Group Invitation", "error");
            }
        });

    }

}
